#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
指定频率功能验证脚本
验证频率合并、去重、测量计算等功能的正确性
"""

import sys
import os

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

def test_frequencies_import():
    """测试frequencies模块导入"""
    print("🔍 测试1: frequencies模块导入")
    try:
        from frequencies import all_frequencies
        print(f"✅ 成功导入frequencies模块")
        print(f"📊 all_frequencies总数: {len(all_frequencies)}")
        print(f"🔢 频率范围: {min(all_frequencies)} - {max(all_frequencies)} MHz")
        
        # 显示部分特殊频率
        sample_freqs = sorted(all_frequencies)[:10]
        print(f"📋 前10个特殊频率: {sample_freqs}")
        return True
    except Exception as e:
        print(f"❌ 导入失败: {str(e)}")
        return False

def test_frequency_generation():
    """测试频率生成和合并逻辑"""
    print("\n🔍 测试2: 频率生成和合并逻辑")
    try:
        from frequencies import all_frequencies
        
        # 模拟常规频率范围
        start_freq = 30
        stop_freq = 6000
        step_freq = 100
        
        # 生成常规频率
        regular_frequencies = []
        current = start_freq
        while current <= stop_freq:
            regular_frequencies.append(current)
            current += step_freq
        
        print(f"📏 常规频率范围: {start_freq}-{stop_freq} MHz, 步进{step_freq} MHz")
        print(f"📊 常规频率点数: {len(regular_frequencies)}")
        
        # 筛选特殊频率
        special_frequencies = [
            freq for freq in all_frequencies 
            if start_freq <= freq <= stop_freq
        ]
        print(f"🎯 范围内特殊频率点数: {len(special_frequencies)}")
        
        # 合并并去重
        combined_frequencies = regular_frequencies + special_frequencies
        unique_frequencies = sorted(list(set(combined_frequencies)))
        
        print(f"🔄 合并前总数: {len(combined_frequencies)}")
        print(f"✨ 去重后总数: {len(unique_frequencies)}")
        print(f"🗑️ 去除重复: {len(combined_frequencies) - len(unique_frequencies)} 个")
        
        # 验证去重效果
        duplicates = len(combined_frequencies) - len(unique_frequencies)
        if duplicates > 0:
            print(f"✅ 去重功能正常，移除了 {duplicates} 个重复频率")
        else:
            print("ℹ️ 无重复频率需要去除")
            
        return True
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        return False

def test_measurement_calculator():
    """测试测量计算器功能"""
    print("\n🔍 测试3: 测量计算器功能")
    try:
        from measurement_calculator import CalibrationCalculator
        
        calculator = CalibrationCalculator()
        
        # 测试参数
        start_freq = 30
        stop_freq = 6000
        step_freq = 100
        start_att = 0
        stop_att = 90
        step_att = 5
        
        print(f"🔧 测试参数:")
        print(f"   频率: {start_freq}-{stop_freq} MHz, 步进{step_freq}")
        print(f"   衰减: {start_att}-{stop_att} dB, 步进{step_att}")
        
        # 测试常规模式
        print("\n📊 常规模式测试:")
        result_regular = calculator.calculate_measurement_count(
            start_freq, stop_freq, step_freq,
            start_att, stop_att, step_att,
            specify_frequency_enabled=False
        )
        
        print(f"   频率点数: {result_regular['frequency_points']}")
        print(f"   衰减点数: {result_regular['attenuation_points']}")
        print(f"   总测量次数: {result_regular['total_measurements']:,}")
        time_str = calculator.format_time_estimation(result_regular['time_estimation'])
        print(f"   预估时长: {time_str}")
        
        # 测试指定频率模式
        print("\n🎯 指定频率模式测试:")
        result_specify = calculator.calculate_measurement_count(
            start_freq, stop_freq, step_freq,
            start_att, stop_att, step_att,
            specify_frequency_enabled=True
        )
        
        print(f"   频率点数: {result_specify['frequency_points']}")
        if 'regular_freq_points' in result_specify:
            print(f"   - 常规频率: {result_specify['regular_freq_points']}")
            print(f"   - 特殊频率: {result_specify['special_freq_points']}")
        print(f"   衰减点数: {result_specify['attenuation_points']}")
        print(f"   总测量次数: {result_specify['total_measurements']:,}")
        time_str = calculator.format_time_estimation(result_specify['time_estimation'])
        print(f"   预估时长: {time_str}")
        
        # 对比分析
        print(f"\n📈 模式对比:")
        increase_ratio = result_specify['total_measurements'] / result_regular['total_measurements']
        print(f"   测量次数增加: {increase_ratio:.1f}x")
        time_increase = result_specify['time_estimation']['total_minutes'] / result_regular['time_estimation']['total_minutes']
        print(f"   时间增加: {time_increase:.1f}x")
        
        return True
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        return False

def test_calibration_thread_logic():
    """测试校准线程逻辑（模拟）"""
    print("\n🔍 测试4: 校准线程频率生成逻辑")
    try:
        # 模拟校准线程的频率生成逻辑
        from frequencies import all_frequencies
        
        # 模拟参数
        start_freq = 2400
        stop_freq = 2500  # 较小范围便于测试
        step_freq = 25
        
        print(f"🔧 测试范围: {start_freq}-{stop_freq} MHz, 步进{step_freq}")
        
        # 生成常规频率
        regular_frequencies = []
        current = start_freq
        while current <= stop_freq:
            regular_frequencies.append(current)
            current += step_freq
        
        print(f"📏 常规频率: {regular_frequencies}")
        
        # 筛选特殊频率
        special_frequencies = [
            freq for freq in all_frequencies 
            if start_freq <= freq <= stop_freq
        ]
        
        print(f"🎯 特殊频率: {sorted(special_frequencies)}")
        
        # 合并去重
        combined = regular_frequencies + special_frequencies
        unique = sorted(list(set(combined)))
        
        print(f"✨ 合并去重后: {unique}")
        print(f"📊 统计: 常规{len(regular_frequencies)} + 特殊{len(special_frequencies)} → 去重后{len(unique)}")
        
        return True
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        return False

def test_ui_calculation_logic():
    """测试UI计算逻辑"""
    print("\n🔍 测试5: UI界面计算逻辑")
    try:
        from measurement_calculator import CalibrationCalculator
        
        calculator = CalibrationCalculator()
        
        # 模拟界面参数更改场景
        scenarios = [
            {"name": "快速测试", "params": (30, 1000, 500, 0, 30, 10)},
            {"name": "标准测试", "params": (30, 3000, 200, 0, 60, 10)},
            {"name": "完整测试", "params": (30, 6000, 100, 0, 90, 5)},
            {"name": "精细测试", "params": (30, 6000, 50, 0, 90, 2.5)},
        ]
        
        print("📋 不同配置对比:")
        print(f"{'配置':>8} | {'常规模式':>12} | {'指定频率':>12} | {'增加倍数':>8}")
        print("-" * 50)
        
        for scenario in scenarios:
            name = scenario["name"]
            sf, ef, step_f, sa, ea, step_a = scenario["params"]
            
            # 常规模式
            regular = calculator.calculate_measurement_count(
                sf, ef, step_f, sa, ea, step_a, False
            )
            
            # 指定频率模式
            specify = calculator.calculate_measurement_count(
                sf, ef, step_f, sa, ea, step_a, True
            )
            
            ratio = specify['total_measurements'] / regular['total_measurements']
            
            print(f"{name:>8} | {regular['total_measurements']:>8,} 次 | {specify['total_measurements']:>8,} 次 | {ratio:>6.1f}x")
        
        return True
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        return False

def test_error_handling():
    """测试错误处理"""
    print("\n🔍 测试6: 错误处理机制")
    try:
        from measurement_calculator import CalibrationCalculator
        
        calculator = CalibrationCalculator()
        
        # 测试异常参数
        print("🔧 测试异常参数处理:")
        
        # 测试步进为0的情况
        try:
            result = calculator.calculate_measurement_count(30, 6000, 0, 0, 90, 5, True)
            print("❌ 应该抛出异常但没有")
        except:
            print("✅ 步进为0时正确处理异常")
        
        # 测试起始频率大于结束频率
        try:
            result = calculator.calculate_measurement_count(6000, 30, 100, 0, 90, 5, True)
            if result['frequency_points'] <= 0:
                print("✅ 频率范围错误时正确处理")
        except:
            print("✅ 频率范围错误时正确抛出异常")
        
        return True
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        return False

def run_comprehensive_verification():
    """运行综合验证"""
    print("=" * 60)
    print("🚀 指定频率功能综合验证")
    print("=" * 60)
    
    tests = [
        test_frequencies_import,
        test_frequency_generation,
        test_measurement_calculator,
        test_calibration_thread_logic,
        test_ui_calculation_logic,
        test_error_handling,
    ]
    
    passed = 0
    total = len(tests)
    
    for test_func in tests:
        try:
            if test_func():
                passed += 1
        except Exception as e:
            print(f"❌ {test_func.__name__} 测试异常: {str(e)}")
    
    print("\n" + "=" * 60)
    print(f"📊 验证结果: {passed}/{total} 项测试通过")
    
    if passed == total:
        print("🎉 所有功能验证通过！指定频率功能实现正确！")
        print("\n✅ 验证要点:")
        print("   - 频率模块导入正常")
        print("   - 频率合并去重逻辑正确")
        print("   - 测量计算器功能完善")  
        print("   - 校准线程逻辑正确")
        print("   - UI计算逻辑准确")
        print("   - 错误处理机制完备")
    else:
        print(f"⚠️ 有 {total - passed} 项测试未通过，请检查相关功能")
    
    print("=" * 60)

if __name__ == "__main__":
    run_comprehensive_verification()